import Utility from '@/utils/utility'

// 检测是否支持webp
function checkWebp() {
  try {
    return (
      document
        .createElement('canvas')
        .toDataURL('image/webp', 0.5)
        .indexOf('data:image/webp') === 0
    )
  } catch (err) {
    return false
  }
}
function imgProcess(url, width, height) {
  if (!url) return ''
  if (!checkWebp() || url.includes('?')) return url
  if (width && height)
    return `${url}?imageMogr2/format/webp/thumbnail/${width}x${height}`
  if (width) return `${url}?imageMogr2/format/webp/thumbnail/${width}x`
  if (height) return `${url}?imageMogr2/format/webp/thumbnail/x${height}`
  return `${url}?imageMogr2/format/webp/thumbnail`
}

// 图片转webp
function getNationImg(currenyId) {
  let url = `${Utility.getOssStaticDomain()}/cross/nationIcons/${currenyId}.png`
  // return  url;
  return `${url}?imageMogr2/format/webp/thumbnail`
}

function fromatPrice(num) {
  return num.toFixed(2)
}

function formatBank(str) {
  if (!str) {
    return ''
  }
  return str.slice(str.length - 4)
}

function formatMoney(num = '0', symbol = '') {
  // replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  // 如果是数字  转字符串
  num = num || '0'
  if (num.constructor === Number) num = num.toString()
  // 如果有小数点
  if (num.includes('.')) {
    let strArr = num.split('.')
    let formatStr = strArr[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    return symbol + formatStr + '.' + strArr[1]
  } else {
    let formatStr = num.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    return symbol + formatStr
  }
}

function formatNumber(num = 0, count = 2) {
  return +num.toFixed(count)
}

export default function (app) {
  app.config.globalProperties.$filters = {
    imgProcess,
    fromatPrice,
    formatBank,
    formatMoney,
    formatNumber,
    getNationImg,
  }
}
